#include "chatwindow.h"
#include "ui_chatwindow.h"
#include "../../network/networkclient.h"
#include "../../../Common/protocol.h"
#include <QDateTime>
#include <QScrollBar>
#include <QKeyEvent>
#include <QMessageBox>
#include <QJsonArray>
#include <QJsonObject>
#include <QCloseEvent>
#include <QHideEvent>
#include <QShowEvent>

ChatWindow::ChatWindow(int currentUserId, int chatWithUserId, 
                       const QString& chatWithName, const QString& chatWithInfo, 
                       QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ChatWindow),
    m_currentUserId(currentUserId),
    m_chatWithUserId(chatWithUserId),
    m_chatWithName(chatWithName),
    m_chatWithInfo(chatWithInfo)
{
    ui->setupUi(this);
    
    // 设置窗口属性
    setWindowTitle("与 " + m_chatWithName + " 的对话");
    setWindowFlags(Qt::Window);
    setAttribute(Qt::WA_DeleteOnClose);
    resize(600, 500);
    
    // 设置顶部信息
    ui->nameLabel->setText(m_chatWithName);
    // 显示额外信息（职称、科室等），如果没有则隐藏
    if (!m_chatWithInfo.isEmpty()) {
        ui->statusLabel->setText(m_chatWithInfo);
    } else {
        ui->statusLabel->hide();
    }
    
    // 设置输入框提示
    ui->inputText->setPlaceholderText("输入消息内容... (Enter发送, Shift+Enter换行)");
    
    // 设置消息显示区域只读
    ui->messageDisplay->setReadOnly(true);
    
    // 连接网络消息
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &ChatWindow::onMessageReceived);
    
    // 连接输入框文本变化
    connect(ui->inputText, &QPlainTextEdit::textChanged,
            this, &ChatWindow::onInputTextChanged);
    
    // 安装事件过滤器以捕获Enter键
    ui->inputText->installEventFilter(this);
    
    // 创建刷新定时器（每3秒刷新一次）
    m_refreshTimer = new QTimer(this);
    connect(m_refreshTimer, &QTimer::timeout, this, &ChatWindow::refreshMessages);
    m_refreshTimer->start(3000);
    
    // 加载历史消息
    loadChatHistory();
    
    // 标记为已读
    markAsRead();
}

ChatWindow::~ChatWindow()
{
    if (m_refreshTimer) {
        m_refreshTimer->stop();
    }
    delete ui;
}

void ChatWindow::closeEvent(QCloseEvent *event) {
    if (m_refreshTimer) {
        m_refreshTimer->stop();
    }
    QDialog::closeEvent(event);
}

void ChatWindow::hideEvent(QHideEvent *event) {
    if (m_refreshTimer) {
        m_refreshTimer->stop();
    }
    QDialog::hideEvent(event);
}

void ChatWindow::showEvent(QShowEvent *event) {
    QDialog::showEvent(event);
    if (m_refreshTimer) {
        m_refreshTimer->start(3000);
        loadChatHistory();
        markAsRead();
    }
}

bool ChatWindow::eventFilter(QObject *obj, QEvent *event) {
    if (obj == ui->inputText && event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        
        // Enter或Return键发送消息（不包括Shift+Enter）
        if ((keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) && 
            !(keyEvent->modifiers() & Qt::ShiftModifier)) {
            sendMessage();
            return true;  // 事件已处理
        }
    }
    
    // 其他事件传递给父类处理
    return QDialog::eventFilter(obj, event);
}

void ChatWindow::loadChatHistory() {
    QJsonObject request;
    request["user_id1"] = m_currentUserId;
    request["user_id2"] = m_chatWithUserId;
    NetworkClient::instance().sendRequest(MSG_GET_CHAT_HISTORY, request);
}

void ChatWindow::refreshMessages() {
    // 定时刷新消息列表
    loadChatHistory();
    // 刷新后标记为已读
    markAsRead();
}

void ChatWindow::displayMessage(const Message& msg) {
    QString html = ui->messageDisplay->toHtml();
    
    // 根据发送者判断左右显示
    bool isSelf = (msg.senderId == m_currentUserId);
    
    // 智能时间显示：今天显示时分，昨天显示"昨天"，更早显示日期
    QString timeStr;
    QDate msgDate = msg.sendTime.date();
    QDate today = QDate::currentDate();
    
    if (msgDate == today) {
        // 今天：只显示时分
        timeStr = msg.sendTime.toString("HH:mm");
    } else if (msgDate == today.addDays(-1)) {
        // 昨天
        timeStr = "昨天 " + msg.sendTime.toString("HH:mm");
    } else if (msgDate.year() == today.year()) {
        // 今年：月-日 时:分
        timeStr = msg.sendTime.toString("MM-dd HH:mm");
    } else {
        // 跨年：年-月-日 时:分
        timeStr = msg.sendTime.toString("yyyy-MM-dd HH:mm");
    }
    
    QString senderName = isSelf ? "我" : m_chatWithName;
    
    if (isSelf) {
        // 自己的消息：右对齐
        html += QString(
            "<div style='text-align:right; margin:10px;'>"
            "<span style='color:#999; font-size:12px;'>%1 %2</span><br>"
            "<span style='background:#95EC69; padding:8px 12px; border-radius:8px; "
            "display:inline-block; max-width:60%; text-align:left;'>%3</span>"
            "</div>"
        ).arg(senderName).arg(timeStr).arg(msg.messageContent.toHtmlEscaped());
    } else {
        // 对方的消息：左对齐
        html += QString(
            "<div style='text-align:left; margin:10px;'>"
            "<span style='color:#999; font-size:12px;'>%1 %2</span><br>"
            "<span style='background:#E0E0E0; padding:8px 12px; border-radius:8px; "
            "display:inline-block; max-width:60%; text-align:left;'>%3</span>"
            "</div>"
        ).arg(senderName).arg(timeStr).arg(msg.messageContent.toHtmlEscaped());
    }
    
    ui->messageDisplay->setHtml(html);
    
    // 滚动到底部
    QScrollBar* scrollBar = ui->messageDisplay->verticalScrollBar();
    scrollBar->setValue(scrollBar->maximum());
}

void ChatWindow::sendMessage() {
    QString content = ui->inputText->toPlainText().trimmed();
    
    if (content.isEmpty()) {
        QMessageBox::warning(this, "提示", "消息内容不能为空");
        return;
    }
    
    Message msg;
    msg.senderId = m_currentUserId;
    msg.receiverId = m_chatWithUserId;
    msg.messageContent = content;
    msg.sendTime = QDateTime::currentDateTime();
    msg.isRead = false;
    
    QJsonObject request = msg.toJson();
    NetworkClient::instance().sendRequest(MSG_SEND_MESSAGE, request);
    
    // 清空输入框
    ui->inputText->clear();
}

void ChatWindow::markAsRead() {
    QJsonObject request;
    request["receiver_id"] = m_currentUserId;
    request["sender_id"] = m_chatWithUserId;
    NetworkClient::instance().sendRequest(MSG_MARK_AS_READ, request);
}

void ChatWindow::on_sendButton_clicked() {
    sendMessage();
}

void ChatWindow::onInputTextChanged() {
    // 限制输入长度（可选）
    if (ui->inputText->toPlainText().length() > 1000) {
        QMessageBox::warning(this, "提示", "消息内容不能超过1000字");
        QString text = ui->inputText->toPlainText();
        text = text.left(1000);
        ui->inputText->setPlainText(text);
        // 移动光标到末尾
        QTextCursor cursor = ui->inputText->textCursor();
        cursor.movePosition(QTextCursor::End);
        ui->inputText->setTextCursor(cursor);
    }
}

void ChatWindow::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_GET_CHAT_HISTORY_RESPONSE) {
        if (data["success"].toBool()) {
            // 清空现有消息
            ui->messageDisplay->clear();
            
            QJsonArray messagesArray = data["messages"].toArray();
            for (const QJsonValue& value : messagesArray) {
                Message msg = Message::fromJson(value.toObject());
                displayMessage(msg);
            }
        }
    }
    else if (type == MSG_SEND_MESSAGE_RESPONSE) {
        if (data["success"].toBool()) {
            // 发送成功，刷新消息列表
            loadChatHistory();
        } else {
            QMessageBox::warning(this, "发送失败", data["message"].toString());
        }
    }
}

